﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;

namespace Tarea4
{
    class ModelNNAStar : ModelBase
    {
        protected override void ModelStart()
        {
            AStar();
            Stop();
        }

        override public int MoveCell(int row, int col)
        {
            return -1;
        }

        override public int UnDoMoveCell()
        {
            return -1;
        }

        public bool AStar()
        {
            Dictionary<StateFifteenManhattan, StateFifteenManhattan> visitedStates = new Dictionary<StateFifteenManhattan, StateFifteenManhattan>();
            PriorityQueue priorityQueue = new PriorityQueue();
            StateFifteenManhattan state = new StateFifteenManhattan(initialBoard);
            StateFifteenManhattan temp;

            priorityQueue.Add(state);

            while(!priorityQueue.IsEmpty)
            {
                if (IsStopped) return false;

                //priorityQueue.PrintQueue();
                state = priorityQueue.GetMin();

                if (state.IsGoalState())
                {
                    NotifyAll(state, "You have reached the goal state!!!", "Depth = " + state.Index + "; Heuristic = " + state.Heuristic);
                    return true;
                }
                ///verificar que no hayamos pasado ya por un estado similar...
                else if (visitedStates.ContainsValue(state))
                {
                    NotifyAll(state, "Depth = " + state.Index + "; Heuristic = " + state.Heuristic, priorityQueue.Count + " states left. Already visited. ");
                    continue;
                }
                else
                {
                    visitedStates.Add(state, state);
                    NotifyAll(state, "Depth = " + state.Index + "; Heuristic = " + state.Heuristic, priorityQueue.Count + " states left.");
                }

                Sleep();

                for(int i  = 0; i < state.Board.GetLength(0); i++)
                    for (int j = 0; j < state.Board.GetLength(0); j++)
                    {
                        temp = (StateFifteenManhattan)state.GetNewState(i, j);
                        if (temp != null)
                        {
                            priorityQueue.Add(temp);
                            //priorityQueue.PrintQueue();
                        }
                    }                
            }

            return false;
        }
    }
}
